package com.ohuang.wallpapermanager.util

import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Rect
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


object BitMapUtil {

    fun cropBitmapToCenter(
        sourceBitmap: Bitmap,
        with: Int,
        height: Int
    ): Bitmap? {
        val cropBitmapToCenter =
            cropBitmapToCenter(sourceBitmap, with.toFloat() / height) ?: return null

        return Bitmap.createScaledBitmap(cropBitmapToCenter, with, height, true)
    }

    fun cropBitmapToCenter(
        sourceBitmap: Bitmap,
        targetAspectRatio: Float   // 目标宽高比
    ): Bitmap? {
        // 获取原始Bitmap的宽度和高度
        val width = sourceBitmap.width
        val height = sourceBitmap.height

        // 计算目标宽度和高度，以保持目标宽高比
        val targetWidth: Int
        val targetHeight: Int
        if (width > height * targetAspectRatio) {
            // 需要根据高度来调整宽度
            targetWidth = (height * targetAspectRatio).toInt()
            targetHeight = height
        } else {
            // 需要根据宽度来调整高度
            targetWidth = width
            targetHeight = (width / targetAspectRatio).toInt()
        }

        // 计算裁剪区域的左上角坐标，确保裁剪的是中间部分
        val x = (width - targetWidth) / 2
        val y = (height - targetHeight) / 2

        // 创建Rect对象，定义裁剪区域
        val rect = Rect(x, y, x + targetWidth, y + targetHeight)

        // 使用Bitmap.createBitmap()进行裁剪
        return Bitmap.createBitmap(
            sourceBitmap,
            rect.left,
            rect.top,
            rect.width(),
            rect.height()
        )
    }

    fun saveBitmap(bm: Bitmap, saveFile: File): Boolean {
        if (saveFile.parentFile != null) {
            saveFile.parentFile?.mkdirs()
        }
        try {
            val saveImgOut = FileOutputStream(saveFile)
            bm.compress(Bitmap.CompressFormat.PNG, 100, saveImgOut)
            saveImgOut.flush()
            saveImgOut.close()
            return true
        } catch (ex: IOException) {
            ex.printStackTrace()
        }
        return false
    }

    /**
     * 缩放到对应尺寸
     *
     * @param bitmap
     * @param toWidth
     * @param toHeight
     * @return
     */
    fun Scale(
        bitmap: Bitmap,
        toWidth: Int,
        toHeight: Int
    ): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val matrix = Matrix()
        matrix.postScale(toWidth * 1.0f / width, toHeight * 1.0f / height)
        return Bitmap.createBitmap(
            bitmap, 0, 0, bitmap.width, bitmap.height,
            matrix, true
        )
    }

}